package com.software.levelupserver.utils;

import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import java.util.Random;

@Component
public class JavaMailUtil {

    @Resource
    private JavaMailSender javaMailSender;

    public  void sendCode(String mail){
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setTo(mail);
        simpleMailMessage.setSubject("serverup-验证码");
        simpleMailMessage.setFrom("2582789555@qq.com");
        String code = createCode();
        simpleMailMessage.setText("验证码："+code+",该验证码30分钟内有效！");
        javaMailSender.send(simpleMailMessage);

        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        servletRequestAttributes.setAttribute(mail,code,1);
        System.out.println(servletRequestAttributes.getSessionId());
    }
    public String createCode(){
        String code = "";
        Random r = new Random();
        for (int i = 0; i < 4; i++){
            int type = r.nextInt(3);
            switch(type){
                case 0:
                    char ch = (char) (r.nextInt(26)+65);
                    code += ch;
                    break;
                case 1:
                    char ch1 = (char)(r.nextInt(26)+97);
                    code += ch1;
                    break;
                case 2:
                    String ch2 = String.valueOf(r.nextInt(10));
                    code += ch2;
                    break;
            }
        }
        return code;
    }
    @Async
    public  void sendMessage(String mail,String subject,String message){
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setTo(mail);
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setFrom("2582789555@qq.com");
        simpleMailMessage.setText(message);
        javaMailSender.send(simpleMailMessage);
    }
}
